#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from flask import request, send_from_directory, render_template
from flask.blueprints import Blueprint
from src import token_required
from src.backend.api import Backend
from src.utils import JSON

__author__ = 'lizige'

logger = logging.getLogger(__name__)
bp = Blueprint("page", __name__)

PATH = None

@bp.route('/static/<path:filename>')
def send_static(filename):
    return send_from_directory('static', filename)


@bp.route("", methods=["GET"])
@token_required
def get_index(jsapi):
    """
    首页
    :param jsapi:
    :return:
    """
    # 申请单类型，1-病理、2-放射、3-超声、4-内镜、5-输血、6-心电图、7-耳鼻喉、8-其他专科检查、9-心电生理、10-神经电生理、11-呼吸
    return render_template("main/reservation/index.html")


@bp.route("/res/info", methods=["GET"])
@token_required
def get_res_info(jsapi):
    """
    申请单详情
    :param jsapi:
    :return:
    """

    return render_template("main/reservation/info.html")


@bp.route("/baodao/list", methods=["GET"])
@token_required
def get_baodao_list(jsapi):
    """
    首页
    :param jsapi:
    :return:
    """
    # 申请单类型，1-病理、2-放射、3-超声、4-内镜、5-输血、6-心电图、7-耳鼻喉、8-其他专科检查、9-心电生理、10-神经电生理、11-呼吸
    type_list = [{"id": "3", "type": "超声"}]
    return render_template("main/baodao/index.html", typeList=type_list)

    return render_template("main/baodao/info.html")


@bp.route("/info", methods=["GET"])
@token_required
def get_info(jsapi):
    """
    申请单详情
    :param jsapi:
    :return:
    """
    sheetID = request.args.get("sheetID", "")
    type = request.args.get("type", "1")

    logger.warning("初始化webservice服务")
    backend = Backend()
    logger.warning("调用RequisitionFind接口")
    QueueName = request.args.get("queueName")
    QueueNumber = request.args.get("queueNumber")
    status, result = backend.RequisitionFind(SheetID=sheetID, RequisitionType=type)
    # status, result = 200, list

    return render_template("main/baodao/info.html",
                           examInfo=result["List"]["RequisitionFindResult"] if status == 200 and result and result[
                               "List"] else None)


@bp.route("/reservation/info", methods=["GET"])
@token_required
def get_reservation_info(jsapi):
    """
    预约回执单
    :param jsapi:
    :return:
    """
    scheduleID = request.args.get("scheduleID", "")
    type = request.args.get("type", "1")

    logger.warning("初始化webservice服务")
    backend = Backend()
    logger.warning("调用RequisitionFind接口")
    # 有预约号则查询的是预约详情，没有预约号则查询的是申请单详情
    status, result = backend.RequisitionFind(ScheduleID=scheduleID, RequisitionType=type)
    # status, result = 200, list
    return render_template("main/baodao/reservationInfo.html",
                           examInfo=result["List"]["RequisitionFindResult"] if status == 200 and result and result[
                               "List"] else None)


@bp.route("/baodao/info", methods=["GET"])
@token_required
def get_baodao_info(jsapi):
    """
    报到回执单
    :param jsapi:
    :return:
    """
    scheduleID = request.args.get("scheduleID", "")
    sheetID = request.args.get("sheetID", "")
    type = request.args.get("type", "1")

    logger.warning("初始化webservice服务")
    backend = Backend()
    logger.warning("调用RequisitionFind接口")
    # QueueName = request.args.get("queueName")
    # QueueNumber = request.args.get("queueNumber")
    # 有预约号则查询的是预约详情，没有预约号则查询的是申请单详情
    if scheduleID:
        status, result = backend.RequisitionFind(ScheduleID=scheduleID, RequisitionType=type)
    else:
        status, result = backend.RequisitionFind(SheetID=sheetID, RequisitionType=type)
    # status, result = 200, list
    return render_template("main/baodao/baodaoInfo.html",
                           examInfo=result["List"]["RequisitionFindResult"] if status == 200 and result and result[
                               "List"] else None)


@bp.route("/baodao/success", methods=["GET"])
@token_required
def get_baodao_success(jsapi):
    """
    报到成功
    :param jsapi:
    :return:
    """
    scheduleID = request.args.get("scheduleID", "")
    sheetID = request.args.get("sheetID", "")
    type = request.args.get("type", "1")

    logger.warning("初始化webservice服务")
    backend = Backend()
    logger.warning("调用RequisitionFind接口")
    if scheduleID:
        status, result = backend.RequisitionFind(ScheduleID=scheduleID, RequisitionType=type)
    else:
        status, result = backend.RequisitionFind(SheetID=sheetID, RequisitionType=type)
    # status, result = 200, list
    return render_template("main/baodao/baodaoSuccess.html",
                           examInfo=result["List"]["RequisitionFindResult"] if status == 200 and result and result[
                               "List"] else None)


@bp.route("/baodao/fail", methods=["GET"])
@token_required
def get_baodao_fail(jsapi):
    """
    报到失败
    :param jsapi:
    :return:
    """
    err = request.args.get("err", "")
    return render_template("main/baodao/baodaoFail.html", err=err)


@bp.route("/reservation/datetime", methods=["GET"])
@token_required
def get_reservation_datetime(jsapi):
    """
    预约时间的选择
    :param jsapi:
    :return:
    """
    return render_template("main/reservation/reservationChange.html")


@bp.route("/reservation/huizhi", methods=["GET"])
@token_required
def get_reservation_huizhi(jsapi):
    """
    预约时间的选择
    :param jsapi:
    :return:
    """
    return render_template("main/reservation/reservationInfo.html")


@bp.route("/reservation/result", methods=["GET"])
@token_required
def get_reservation_result(jsapi):
    """
    预约结果页
    :param jsapi:
    :return:
    """
    status = request.args.get("status")
    type = request.args.get("type")
    err = request.args.get("err")

    if status == "1":
        sheetIdList = request.args.get("id").split(",")
        successList = []
        errorList = []
        if (len(sheetIdList) > 1):
            for sheetId in sheetIdList:
                status, result = jsapi.reservation_api.GETPOST_Request_GetById(id=sheetId)
                if status == 200:
                    if result["data"]["ReservationState"] == 1:
                        successList.append(result["data"])
                    else:
                        errorList.append(result["data"])
            return render_template("main/reservation/reservationResult.html", status=status, successList=successList,
                                   errorList=errorList, err=err)
        else:
            status, result = jsapi.reservation_api.GETPOST_Request_GetById(id=sheetIdList[0])
            return render_template("main/reservation/reservationSuccess.html", exam=result["data"], type=type)
    else:
        return render_template("main/reservation/reservationFail.html", err=err, type=type)


@bp.route("/baodao/queue", methods=["GET"])
@token_required
def get_baodao_queue(jsapi):
    """
    排队信息
    :param jsapi:
    :return:
    """
    waitingInfo = {"image_url": "", "dept_name": "fads", "zs_name": "dfsd", "queue_num": 2}
    waitingInfo = [{"QueueName": "超声A队列", "QueueNumber": "排队号", "NumberOfFront": "10", "QueueStatus": "排队中,已叫号,已过号",
                    "CallingRoom": "叫号诊间", "SheetId": "1", "PatientId": "患者ID", "FloorName": "住院楼2楼-楼层名称"}]
    SheetIds = ["1", "2", "3"]
    PatientId = "test"
    # status, result = jsapi.app_api.POST_Queue_QueryQueueStatus(SheetIds=JSON.dumps(SheetIds), PatientId=PatientId)
    # waitingInfo = result["data"]
    # 开始推送提醒接口
    # params = {
    #     "hospital_id": "086bab30-f874-4b43-949a-be0e713f11b0",
    #     "msg_id": "10",
    #     "msg_name": "检查报到提醒",
    #     "data": [
    #         {
    #             "push_id": "1ac843bf-5b3d-4523-bfbf-c77fc2345d8e25",
    #             "patientid": "",
    #             "openid": "",
    #             "msg_content": "您好，您已经报到成功，请注意叫号，谢谢！（测试）"
    #
    #         }
    #     ]
    # }
    # params['data'][0]['patientid'] = jsapi.user_id
    # status1, result1 = jsapi.push_api.post(params=JSON.dumps(params))
    # logger.warning("完成推送：%s:%s", str(status1), str(result1))
    return render_template("main/baodao/queue.html")


@bp.route("/search", methods=["GET"])
def get_search():
    return render_template("main/reservation/writeInfo.html")
